
var Agent = function() {

    var datalist_url = $('.datalist_url').val();
    var view_url = $('.view_url').val();
    var edit_url = $('.edit_url').val();
    var recharge_url = $('.recharge_url').val();
    var delete_url = $('.delete_url').val();
    var redirect_url = $('.redirect_url').val();
    var parentIdList_url = $('.parentIdList_url').val();
    var tenantList_url = $('.tenantList_url').val();
    var openLogList_url = $('.openLogList_url').val();
    var district_url = $('.district_url').val();

    var isLoadOpenLogTable = false;


    /**
     * 代理商 table
     */
    var initTable = function() {
        var table = $('#data-table');

        if(table.length > 0){
            table.dataTable({
                "processing": true,
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url: datalist_url,
                },
                "autoWidth": false,
                "columns": [
                    {"data": "name"},
                    {"data": "levelName"},
                    /*{"data": "fullAddress"},*/
                    {
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            if(row.province){
                                return row.province + ' - ' + row.city;
                            }else{
                                return '';
                            }
                        }
                    },
                    {
                        "data": "rechargeAmount",
                        "render": function(data, type, row, meta) {
                            if(data){
                                return data / 100 + ' 元';
                            }
                            return data;
                        }
                    },
                    {"data": "contactUser"},
                    {"data": "phone"},
                    {
                        "data": "createDate",
                        "render": function(data, type, row, meta) {
                            return data;
                        }
                    },
                    {
                        "width": "20%",
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            return '<a href="'+view_url+'?id='+encodeURIComponent(row.id)+'" type="button" class="btn btn-info">详情</a>' +
                                '<a href="'+edit_url+'?id='+encodeURIComponent(row.id)+'" type="button" class="btn btn-success">编辑</a>' +
                                '<button type="button" class="btn purple recharge-btn">充值</button>' +
                                '<button type="button" class="btn btn-danger delete-btn">删除</button>';
                        }
                    }
                ],
                "language": {
                    url: '/public/static/agent/pages/datatable_cn.json'
                },
                "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
                "pageLength": 10,
                "scrollX":"",
                "destroy": false,
                "stateSave": false,
                "stateSaveParams": function (settings, data) {
                    /*var search = data.search.search;
                    if(search){
                        var arr = $.parseJSON(search);
                        for(var key in arr){
                            $("#searchForm input[name='"+key+"']").val(arr[key]);
                            $("#searchForm select[name='"+key+"']").val(arr[key]);
                        }
                    }*/
                },
                "order": [
                    [6, "desc"]
                ],
                "columnDefs": [{
                    "orderable": false,
                    "targets": [0, 1, 2, 4, 5, 7]
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'relative'<'col-md-5'i><'col-md-7'>lp>",
                "fnInitComplete": function() {
                    var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
                }
            });
        }

        // 筛选
        $('#doSearch').on('click', function(event){
            /*var name = $("#search input[name='name']").val();
            var level = $("#search select[name='level']").val();
            var district = $("#search select[name='district']").val();
            var start_amount = $("#search input[name='start_amount']").val();
            var end_amount = $("#search input[name='end_amount']").val();
            var contactUser = $("#search input[name='contactUser']").val();
            var phone = $("#search input[name='phone']").val();
            var param = {
                'name' : name,
                'level' : level,
                'district' : district,
                'start_amount' : start_amount,
                'end_amount' : end_amount,
                'contactUser' : contactUser,
                'phone' : phone,
            };*/
            var param = $('#search').serializeObject();

            tableSearch(table, param);
        });

        // 充值
        table.on('click', '.recharge-btn', function(event) {
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var _this = $(this);

            var url = recharge_url;
            var data = {'id': id};
            $.ajax({
                url: url,
                type: 'POST',
                data: data,
                dataType: 'json',
                success: function (data) {
                    if (data.status == 1) {
                        var _html = data.data;
                        if($('body').find('#recharge-modal').length){
                            $('body').find('#recharge-modal').remove();
                        }

                        $('body').append(_html);
                        $('#recharge-modal').modal('show');
                    }else{
                        layer.msg(data.msg);
                    }
                }
            });
        });

        // 删除
        table.on('click', '.delete-btn', function(event) {
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var _this = $(this);

            var text = '是否要删除该代理商？';
            var title = '请确认';
            var confirmBtn = '确定';
            var cancelBtn = '取消';
            event.preventDefault();
            layer.confirm(
                text,
                {
                    title: title,
                    btn: [confirmBtn, cancelBtn]
                },
                function(index){
                    layer.close(index);
                    var url = delete_url;
                    var data = {'id':id};
                    $.ajax({
                        url: url,
                        type: 'POST',
                        data: data,
                        dataType : 'json',
                        success: function (data) {
                            layer.msg(data.msg);
                            if(data.status == 1){
                                _this.parents('tr').remove();
                            }
                        }
                    });
                }
            );
        });

    };

    /**
     * 上级代理 table
     */
    var parentIdTable = function() {
        var table = $('#parentId_table');
        var id = $('input[name=id]').val();
        var levelId = $('select[name=levelId]').val();

        if(table.length > 0){
            table.dataTable({
                "processing": true,
                "ordering": false, // 禁止排序
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url: parentIdList_url,
                    data: {
                        'id': id,
                        'levelId': levelId
                    }
                },
                "autoWidth": false,
                "columns": [
                    {"data": "name"},
                    {"data": "levelName"},
                    /*{"data": "fullAddress"},*/
                    {
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            if(row.province){
                                return row.province + ' - ' + row.city;
                            }else{
                                return '';
                            }
                        }
                    },
                    {
                        "width": "20%",
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            return '<button type="button" class="btn purple doSelect">选择</button>';
                        }
                    }
                ],
                "language": {
                    url: '/public/static/agent/pages/datatable_cn.json'
                },
                "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
                "pageLength": 10,
                "scrollX":"",
                "destroy": false,
                "stateSave": false,
                "stateSaveParams": function (settings, data) {
                    /*var search = data.search.search;
                    if(search){
                        var arr = $.parseJSON(search);
                        for(var key in arr){
                            $("#searchForm input[name='"+key+"']").val(arr[key]);
                            $("#searchForm select[name='"+key+"']").val(arr[key]);
                        }
                    }*/
                },
                "columnDefs": [{
                    "orderable": false,
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                    "<t>" +
                    "<'relative'<'col-md-5'i><'col-md-7'>lp>",
                "fnInitComplete": function() {
                    var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
                }
            });
        }

        // 筛选
        $('#doSearch').on('click', function(event){
            var id = $('input[name=id]').val();
            var levelId = $('select[name=levelId]').val();
            var name = $("#search input[name='name']").val();
            var param = {
                'id': id,
                'levelId': levelId,
                "name" : name,
            };

            tableSearch(table, param);
        });

        // 选择
        table.on('click', '.doSelect', function(event) {
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var name = dataArr[0].name;

            $('input[name=parentId]').val(id);
            $('#parentId').val(name);
            $('#parentId-modal').modal('hide');
        });
    };

    /**
     * 开通商户 table
     */
    var tenantTable = function() {
        var table = $('#tenant_table');
        var id = $('input[name=agentId]').val();

        if(table.length > 0){
            table.dataTable({
                "processing": true,
                "ordering": false, // 禁止排序
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url: tenantList_url,
                    data: {
                        'id': id,
                    }
                },
                "autoWidth": false,
                "columns": [
                    {"data": "code"},
                    {"data": "name"},
                    {"data": "category"},
                    {
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            if(row.province){
                                return row.province + ' - ' + row.city;
                            }else{
                                return '';
                            }
                        }
                    },
                    {"data": "loginName"},
                    {"data": "phone"},
                    {
                        "data": "createDate",
                        "render": function(data, type, row, meta) {
                            return data;
                        }
                    },
                ],
                "language": {
                    url: '/public/static/agent/pages/datatable_cn.json'
                },
                "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
                "pageLength": 10,
                "scrollX":"",
                "destroy": false,
                "stateSave": false,
                "stateSaveParams": function (settings, data) {
                    /*var search = data.search.search;
                    if(search){
                        var arr = $.parseJSON(search);
                        for(var key in arr){
                            $("#searchForm input[name='"+key+"']").val(arr[key]);
                            $("#searchForm select[name='"+key+"']").val(arr[key]);
                        }
                    }*/
                },
                "columnDefs": [{
                    "orderable": false,
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'relative'<'col-md-5'i><'col-md-7'>lp>",
                "fnInitComplete": function() {
                    var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
                }
            });
        }
    };

    /**
     * 开通商户记录 table
     */
    var openLogTable = function() {
        var table = $('#openLog_table');
        var id = $('input[name=agentId]').val();

        if(table){
            table.dataTable({
                "processing": true,
                "ordering": false, // 禁止排序
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url: openLogList_url,
                    data: {
                        'id': id,
                    }
                },
                "autoWidth": false,
                "columns": [
                    {"data": "code"},
                    {"data": "name"},
                    {
                        "data": "createDate",
                        "render": function(data, type, row, meta) {
                            return data;
                        }
                    },
                    {
                        "data": "openCost",
                        "render": function(data, type, row, meta) {
                            return data / 100;
                        }
                    },
                ],
                "language": {
                    url: '/public/static/agent/pages/datatable_cn.json'
                },
                "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
                "pageLength": 10,
                "scrollX":"",
                "destroy": false,
                "stateSave": false,
                "stateSaveParams": function (settings, data) {
                    /*var search = data.search.search;
                    if(search){
                        var arr = $.parseJSON(search);
                        for(var key in arr){
                            $("#searchForm input[name='"+key+"']").val(arr[key]);
                            $("#searchForm select[name='"+key+"']").val(arr[key]);
                        }
                    }*/
                },
                "columnDefs": [{
                    "orderable": false,
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'relative'<'col-md-5'i><'col-md-7'>lp>",
                "fnInitComplete": function() {
                    var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
                }
            });
        }

        isLoadOpenLogTable = true;
    };

    /**
     * Table 筛选
     * @param table
     * @param params
     */
    var tableSearch = function(table, params) {

        table.DataTable().search(JSON.stringify(params)).draw();
    };

    // 初始化地址
    /*var initAddress = function() {
        var province = $('.province').val(),
            city = $('.city').val(),
            district = $('.district').val();
        if(province){
            $("#province").val(province);
            change(1);
            if(city){
                $("#city").val(city);
                change(2);
                if(district){
                    $("#district").val(district);
                }
            }
        }
    };*/


    return {
        init: function() {
            initTable();
            parentIdTable();
            tenantTable();
            //openLogTable();
            //initAddress();

            this.onEvent();
        },

        onEvent : function(){

            // 选择代理级别
            $('#levelId').on('change', function () {
                var text = $(this).find('option:selected').text();
                $('input[name=levelName]').val(text);
            });

            // 充值提交
            $(document).on('click', '.recharge-save', function () {
                var amount = $('input[name=recharge_money]').val();
                if(!mdTool.validate(amount, 'two') || amount == 0){
                    layer.msg('充值金额应大于0，且小数点后只有两位！');
                    $('input[name=recharge_money]').focus();
                    return false;
                }

                $('#recharge-modal').modal('hide');
                var url = $('#recharge-modal').find('#ajax-form').attr('action');
                var data = $('#recharge-modal').find('#ajax-form').serialize();
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: data,
                    dataType: 'json',
                    success: function (data) {
                        layer.msg(data.msg);
                        window.location.reload();
                    }
                });
                return false;
            });

            // 所在地区选择
            $('.district').on('click', function(){
                var url = district_url;
                var data = {};
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: data,
                    dataType: 'json',
                    success: function (data) {
                        if (data.status == 1) {
                            var _html = data.data;
                            if($('body').find('#district-modal').length){
                                $('body').find('#district-modal').remove();
                            }

                            $('body').append(_html);
                            $('#district-modal').modal('show');
                        }else{
                            layer.msg(data.msg);
                        }
                    }
                });
            });
            $(document).on('click', '.confirm-district', function () {
                var obj = $('#district-modal').find('input[name=district]');
                var check_val = [];
                for(i in obj){
                    if(obj[i].checked){
                        check_val.push(obj[i].value);
                    }
                }
                //console.log(check_val);
                $('.district').val(check_val);
                $('#district-modal').modal('hide');
            });

            /**
             * 表单提交
             */
            $('.save-btn').on('click', function () {
                var _form = $('#ajax-form');
                //var _formData = $('#ajax-form').serializeObject();
                if(ajaxForm.name.value.trim() == ''){
                    layer.msg('代理商名称不能为空！');
                    ajaxForm.name.focus();
                    return false;
                }
                if(ajaxForm.name.value.length > 40){
                    layer.msg('代理商名称最长为40个字符！');
                    ajaxForm.name.focus();
                    return false;
                }
                var first_level_id = $('#levelId').find('option:first-child').val();
                var level_id = $('#levelId').find('option:selected').val();
                if(level_id != first_level_id){
                    var parentId = $('input[name=parentId]').val();
                    if(parentId == 0){
                        layer.msg('请选择所属上级！');
                        return false;
                    }
                }

                var province = $('input[name=province]').val();
                if(!mdTool.validate(province, 'require') || province == '省份'){
                    layer.msg('请选择省份！');
                    return false;
                }
                var city = $('input[name=city]').val();
                if(!mdTool.validate(city, 'require') || city == '地级市'){
                    layer.msg('请选择城市！');
                    return false;
                }
                /*if(!mdTool.validate(ajaxForm.rechargeAmount.value, 'two') || ajaxForm.rechargeAmount.value == 0){
                    layer.msg('充值金额应大于0，且小数点后只有两位！');
                    ajaxForm.rechargeAmount.focus();
                    return false;
                }*/
                if(ajaxForm.loginName.value.trim() == ''){
                    layer.msg('账号不能为空！');
                    ajaxForm.loginName.focus();
                    return false;
                }
                if(ajaxForm.loginName.value.length > 11){
                    layer.msg('账号最长为11个字符！');
                    ajaxForm.loginName.focus();
                    return false;
                }
                // 添加时验证
                if(!$('input[name=ori_password]').val()){
                    if(ajaxForm.password.value.trim() == ''){
                        layer.msg('密码不能为空！');
                        ajaxForm.password.focus();
                        return false;
                    }
                }
                if(ajaxForm.password.value.trim()){
                    if(ajaxForm.password.value.length < 6 || ajaxForm.password.value.length > 12){
                        layer.msg('密码长度在6-12位之间！');
                        ajaxForm.password.focus();
                        return false;
                    }
                    if(ajaxForm.password.value != ajaxForm.confirm_password.value){
                        layer.msg('两次密码不一致！');
                        ajaxForm.confirm_password.focus();
                        return false;
                    }
                }

                if(!mdTool.validate(ajaxForm.phone.value, 'phone')){
                    layer.msg('手机号格式不正确！');
                    ajaxForm.phone.focus();
                    return false;
                }

                var url = _form.attr('action');
                var data = _form.serialize();
                layer.load(2, {shade: [0.8,'#000000']}); // 打开loading
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: data,
                    dataType : 'json',
                    success: function (data) {
                        layer.closeAll('loading'); // 关闭loading
                        layer.msg(data.msg);
                        if(data.status == 1){
                            window.location.href = redirect_url;
                        }
                    }
                });
                return false;
            });

            // 所属上级
            $('#parentId').on('click', function(){
                $('#parentId_table').find('tbody').empty();
                var table = $('#parentId_table');
                var id = $('input[name=id]').val();
                var levelId = $('select[name=levelId]').val();
                var param = {
                    'id' : id,
                    'levelId' : levelId,
                    'name' : '',
                };
                tableSearch(table, param);
            });

            // 开通记录
            $('.open-log').on('click', function(){
                if(!isLoadOpenLogTable){
                    openLogTable();
                }
            });
        }
    };

}();


$(function() {
    Agent.init();

});
